package com.fowo.api.service.handleWork;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.fowo.api.entity.Product;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVo;
import com.fowo.api.model.requisition.RequisitionConfirmationTransferAction;
import com.fowo.api.model.requisition.RequisitionVo;
import com.fowo.api.model.requisition.product.RequisitionProductItemVo;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.model.stock.out.StockOutVo;
import com.fowo.api.model.stock.out.product.StockOutProductItemVo;
import com.fowo.api.service.RequisitionService;
import com.fowo.api.service.StockInService;
import com.fowo.api.service.StockOutService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 调拨单的确认调拨行为接口
 */
@Component
public class RequisitionConfirmationTransfer implements RequisitionConfirmationTransferAction {

    @Resource
    private RequisitionService requisitionService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private StockInService stockInService;
    @Resource
    private StockOutService stockOutService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run(Long id) throws Exception {
        RequisitionVo requisition = requisitionService.getVoById(id);
        Assert.notNull(requisition,"调拨单不存在");
//        Assert.isTrue(requisition.getStatus().equals("1"),"当前单据状态不可进行此操作！");
        requisition.getType();
        switch (requisition.getType()){
            case "1": //简易调拨
                requisition.setStatus("3");
                createStockOut(requisition);
//                requisitionService.goodOut(id);
//                requisitionService.badOut(id);
                requisitionService.lockGoodOut(id);
                requisitionService.lockBadOut(id);

                createStockIn(requisition);
                requisitionService.goodIn(id);
                requisitionService.badIn(id);
                break;
            case "2": //完整调拨
                requisition.setStatus("2");
                createStockOut(requisition);
//                requisitionService.goodOut(id);
//                requisitionService.badOut(id);
                requisitionService.lockGoodOut(id);
                requisitionService.lockBadOut(id);
                break;
            default:
                break;
        }

        // 释放库存
//        requisitionService.releaseGoodInventory(id);
//        requisitionService.releaseGoodInventoryBin(id);
//        final Integer badSum = requisition.getRequisitionProduct().stream().filter(t->t.getDefectiveRqtQuantity()!=null).mapToInt(p -> p.getDefectiveRqtQuantity()).sum();
//        if(badSum > 0){
//        }
//        requisitionService.releaseBadInventory(id);
//        requisitionService.releaseBadInventoryBin(id);

        requisitionService.update(requisition);
    }

    /**
     * 添加入库单
     * @param requisition
     * @throws Exception
     */
    public void createStockIn(RequisitionVo requisition) throws Exception {
        StockInVo stockInVo = new StockInVo();
        stockInVo.setWarehouse(requisition.getToWid());
        stockInVo.setReceiptType("RK005");
        stockInVo.setRemarks("调拨单号："+requisition.getRqtSn());
        stockInVo.setCostAllocationType("1");
        stockInVo.setWarehousingDate(new Date());
        stockInVo.setPurchaseOrderCode(requisition.getRqtSn());
        stockInVo.setStatus("1");
        List<StockInProductItemVo> productList = new ArrayList<>();
        for(RequisitionProductItemVo item : requisition.getRequisitionProduct()){
            Product product = productMapper.selectById(item.getProductId());
            Assert.notNull(product,"商品不存在，请检查");
            StockInProductItemVo productItemVo = new StockInProductItemVo();
            productItemVo.setImg(item.getImg());
            productItemVo.setProductId(item.getProductId());
            productItemVo.setSku(item.getSku());
            BigDecimal quantity = NumberUtil.add(item.getAvailbleRqtNum(), item.getDefectiveRqtQuantity());
            productItemVo.setUnitStock(Convert.toInt(quantity));
            productItemVo.setQuantity(item.getAvailbleRqtNum());
//            productItemVo.setGoodProduct(item.getAvailbleRqtNum());
            productItemVo.setPositions(item.getToGoodWarehouseBin());
            productItemVo.setDefectiveProduct(item.getDefectiveRqtQuantity());
            productItemVo.setDefectiveProductPosition(item.getToBadWarehouseBin());
            BigDecimal procurementCost = product.getProcurementCost() == null ? new BigDecimal(0.00) : product.getProcurementCost();
            productItemVo.setUnitPrice(procurementCost);
            productItemVo.setUnitReceiptCost(procurementCost);
            productItemVo.setSubtotal(BigDecimal.valueOf(item.getAvailbleRqtNum()).multiply(procurementCost));
            productItemVo.setShopId(item.getShopName());
            productItemVo.setLxFnsku(item.getFnsku());
            productList.add(productItemVo);
        }
        stockInVo.setProductList(productList);

        stockInService.create(stockInVo);
    }

    /**
     * 添加出库单
     * @param requisition
     * @throws Exception
     */
    public void createStockOut(RequisitionVo requisition) throws Exception {
        StockOutVo stockOutVo = new StockOutVo();
        stockOutVo.setWarehouse(requisition.getWid());
        stockOutVo.setType("CK005");
        stockOutVo.setOutTime(new Date());
        stockOutVo.setRemark("调拨单号："+requisition.getRqtSn());
        stockOutVo.setStatus("CS02");
        stockOutVo.setCustomSourceSn(requisition.getRqtSn());
        List<StockOutProductItemVo> stockOutProducts = new ArrayList<>();
        for(RequisitionProductItemVo item : requisition.getRequisitionProduct()){
            Product product = productMapper.selectById(item.getProductId());
            Assert.notNull(product,"商品不存在，请检查");
            StockOutProductItemVo productItemVo = new StockOutProductItemVo();
            productItemVo.setProductImg(item.getImg());
            productItemVo.setProductId(item.getProductId());
            productItemVo.setSku(item.getSku());
            productItemVo.setSid(item.getShopName());
            productItemVo.setShopName(item.getShopNameShopName());
            productItemVo.setFnsku(item.getFnsku());
            productItemVo.setProductGoodNum(item.getAvailbleRqtNum());
            productItemVo.setStorageBinGoodId(item.getFromGoodWarehouseBin());
            productItemVo.setProductBadNum(item.getDefectiveRqtQuantity());
            productItemVo.setStorageBinBadId(item.getFromBadWarehouseBin());
            double quantity = NumberUtil.add(item.getAvailbleRqtNum() == null ? 0 : item.getAvailbleRqtNum(), item.getDefectiveRqtQuantity() == null ? 0 : item.getDefectiveRqtQuantity());
            productItemVo.setQuantity(Convert.toInt(quantity));
            BigDecimal procurementCost = product.getProcurementCost() == null ? new BigDecimal(0.00) : product.getProcurementCost();
            productItemVo.setPrice(procurementCost);
            productItemVo.setSubtotal(BigDecimal.valueOf(Math.abs(item.getAvailbleRqtNum() == null ? 0 : item.getAvailbleRqtNum())).multiply(procurementCost));

            stockOutProducts.add(productItemVo);
        }
        stockOutVo.setStockOutProducts(stockOutProducts);
        stockOutService.create(stockOutVo);
    }
}
